package models

import (
	"fmt"
	"WDserver/config"
	"WDserver/util"
	"strconv"
	"time"
)



func InstallUser(user ,passwd ,email ,ip string) string {
	a := new(Account)
	has, _ := ADB.ID(user).Get(a)
		if has == true {
			return "msg|该用户已存在，请重新注册！"
		}
	a.Account = user
	a.Password = util.Md5Passwd(a.Account, passwd)
	a.GoldCoin = config.Config().Jyb
	a.SilverCoin = config.Config().Yyb
	a.Privilege = config.Config().Privilege
	a.Checksum = util.Checksum(a.Account, a.Password, config.Config().Privilege, config.Config().Jyb, config.Config().Yyb)
	_, err := ADB.Insert(a)
		if err !=nil {
			return "msg|注册失败！"
			}
	b := new(User)
	b.Account = user
	b.Passwd = passwd
	b.Email = email
	b.Ip = ip
	_, err1 := WG.Insert(b)
		if err1 !=nil {
			return "msg|注册失败！"
			}
	return "msg|恭喜你！注册成功！"

}

func UpdateUser(user, oldpwd, newpwd string) string {
	a := new(Account)
	rows,_ := ADB.ID(user).Get(a)
	if  rows == false{
		return "msg|该用户不存在！"
	}
	if util.Md5Passwd(a.Account, oldpwd) != a.Password {
		return "msg|旧密码错误，请重新输入！（如果忘记旧密码，请联系管理员重置密码！）"
	}
	a.Password = util.Md5Passwd(a.Account, newpwd)
	a.Checksum = util.Checksum(a.Account, a.Password, a.Privilege, a.GoldCoin, a.SilverCoin)
	_, err := ADB.ID(a.Account).Update(a)
	if err != nil{
		return "msg|修改失败！"
	}
	wg := new(User)
	wg.Passwd = newpwd
	_, err1 := WG.ID(a.Account).Update(wg)
	if err1 != nil{
		return "msg|修改失败！"
	}
	return "msg|修改密码成功！"
}


func UpdateCDK(user, cdk string) string {
	a := new(Account)
	b := new(Cdk)
	rows,_ := ADB.ID(user).Get(a)
		if  rows == false{
			return "msg|该用户不存在！"
		}
	rows1,_ := WG.ID(cdk).Get(b)
		if  rows1 == false{
			return "msg|CDK码不存在！"
		}
		if b.Used == 1 {
			return "msg|CDK码已被使用！"
		}
	a.GoldCoin = a.GoldCoin + b.Jyb
	a.SilverCoin = a.SilverCoin + b.Yyb
		if a.GoldCoin > 2000000000 {
			return "msg|土豪！！！亲！你所使用的CDK码金元宝数已超过有效范围！请您先消费一下在兑换！"
		}
		if a.SilverCoin > 2000000000 {
			return "msg|土豪！！！亲！你所使用的CDK码银元宝数已超过有效范围！请您先消费一下在兑换！"
		}
	a.Checksum = util.Checksum(a.Account, a.Password, a.Privilege, a.GoldCoin, a.SilverCoin)
	_, err := ADB.ID(a.Account).Update(a)
		if err != nil{
			return "msg|CDK兑换失败！"
		}
	b.Account = user
	b.UseTime = time.Now().Format("2006-01-02 15:04:05")
	b.Used = 1
	_, err1 := WG.ID(b.Cdk).Update(b)
		if err1 != nil{
			return "msg|CDK兑换失败！"
		}

	return "msg|兑换成功！你现在拥有的金元宝数量：" + strconv.Itoa(a.GoldCoin) + "元宝 ，银元宝数量：" + strconv.Itoa(a.SilverCoin) + "元宝。"

}

func LockIP(ip string) bool {
	user := new(User)
	rows, err := WG.Where("ip=?", ip).Rows(user)
	if err != nil {
		fmt.Println("查找IP失败！")
	}
	defer rows.Close()
	record := make(map[string]int)
	for rows.Next() {
		var str []string
		err = rows.Scan(user)
		if err != nil {
			fmt.Println("IP遍历失败！")
		}
		str = append(str,user.Ip)
		for _, v := range str {
			if record[v] != 0 {
				record[v]++
			} else {
				record[v] = 1
			}
		}
	}
	for k, v := range record {
		if v >= config.Config().IPLock {
			if k == ip {
				return true
			}
		}
	}
	return false
}


